<!--
 描述: 主页模板
 作者: Jack Chen
 日期: 2020-06-15
-->

<template>
    <div class="home-container">
        <Header />
  
      <div class="content clearfix">
        <div class="list">
          <Form :model="formFind" ref="formFind" style="flex-wrap: wrap;">
            <Col span="5">
                <FormItem label="词汇包名字：" prop="name" label-position="left" :label-width=120>
                    <Input v-model="formFind.name" placeholder="请输入词汇包名字" />
                </FormItem>
            </Col>
            <Col span="9">
                <FormItem label="创建时间：" prop="gmt_create" label-position="left" :label-width=90>
                  <DatePicker :editable="false" v-model="formFind.gmt_create" type="daterange" placeholder="请选择日期范围"></DatePicker>
                </FormItem>
            </Col>
            <Col span="4" style="text-align:center">
                <Button type="primary" icon="md-search" size="large" @click="getTaskList">查找词汇包</Button>
            </Col>
            <Col span="3" style="text-align:center">
                <Button type="info" icon="md-trash" size="large" @click="handleReset('formFind')">重置</Button>
            </Col>
            <!-- <Col span="3" style="text-align:center">
                <Button type="success" icon="md-add" size="large" @click="addTask">添加词汇包</Button>
            </Col> -->
            <Col span="3" style="text-align:center">
                <Button type="success" icon="md-add" size="large" @click="importTask">导入词汇包</Button>
                <input ref="upFileExcel" name="file" type="file" style="display: none" @change="doImport">
            </Col>
          </Form>
            
        </div>
  
        <Table style='min-height: 60vmin;' :loading="loading" :columns="columns" :data="tableData">
          <template slot-scope="{ row, index }" slot="action">
           
            <Button type="primary" ghost style="margin-right: 10px" @click="edit(index)">编辑</Button>
            <Button type="error" ghost @click="remove(row.id)">删除</Button>
          </template>
        </Table>
  
        <Page
          class-name="pagination"
          show-total
          show-sizer
          :total="total"
          @on-page-size-change="handlePageSizeChange"
          @on-change="handleCurrentChange"
          :page-size="pageSize"
          :page-size-opts="pageSizeOpts"
          :current="pageNo"
          v-if="!loading && total > 0"
        />
      </div>
  
      <Footer />
  
      <Drawer
        :title="title"
        v-model="isShow"
        width="600"
        :styles="styles"
        :mask-closable="true"
      >
        <Form :model="formValidate" ref="formValidate" :rules="ruleValidate">
          <Col span="15" v-if="normalUserID==0">
                <FormItem label="词汇包名字：" prop="name" label-position="left" :label-width=120>
                    <Input v-model="formValidate.name" placeholder="请输入词汇包名字：" :disabled="type<=0"/>
                </FormItem>
            </Col>
            <Col span="16">
                <FormItem label="创建时间：" prop="gmt_create" label-position="left" :label-width=85>
                  <DatePicker :editable="false" v-model="formValidate.gmt_create" type="datetime" placeholder="请选择创建时间" :disabled="type<=0"></DatePicker>
                </FormItem>
            </Col>
            <Col span="15">
                <FormItem label="图片：" prop="image" label-position="left" :label-width=85>
                    <img :src="apiUrl+formValidate.image" style="width: 100px;" />
                    <input ref="upFileImage" name="file" type="file" @change="doImportImage" />
                </FormItem>
            </Col>
        </Form>
        <div class="demo-drawer-footer">
          <Button type="primary" style="margin-right: 15px" @click="handleSubmit('formValidate')" v-if="type>0">{{ textBtn }}</Button>
          <Button @click="handleReset('formValidate')" style="margin-right: 15px" v-if="type>0">重置</Button>
          <Button type="error" ghost @click="isShow = false" v-if="type>0">取消</Button>
        </div>
      </Drawer>    
  
  
    </div>
  </template>
  
  <script>
  import Header from '@/components/Header';  
  import Footer from '@/components/Footer'; 
  import store from '../store'
  import { 
    formatTime,
    formatDate
  } from '@/utils/valid';
  import { 
    getBookList,
    addBook,
    editBook,
    deleteBook,
    importBook,
    uploadFile
  } from '@/utils/api';
  import {uploadUrl} from '@/utils/url';
  
  export default {
    name: 'Home',
    components: {
      Header,
      Footer
    },
    data() {
        return {
          normalUserID: 0,
          loading: true,
          total: 0,
          pageNo: 1,
          pageSize: 100,
          pageSizeOpts: [10,50,100,200],
          textBtn: '提交',
          type: 1, // 1:添加 2:编辑
          title: '添加词汇包',
          isShow: false,
          deleteId: 0,  // 临时保存删除id
          styles: {
            height: 'calc(100% - 55px)',
            overflow: 'auto',
            paddingBottom: '53px',
            position: 'static'
          },
          formFind: {
            name: '',
            gmt_create: [],
          },
          formValidate: {
            id: 0,
            name: '',
            gmt_create: formatTime(new Date()),
          },
          columns: [
            {
              title: '词汇包名字',
              key: 'name',
              width: 300,
              align: 'center',
              sortable: true
            },
            {
              title: '图片',
              key: 'image',
              width: 250,
              render: (h, params) => {
                const row = params.row;
                return h('img', {
                  style: {
                    height: "32px"
                  },
                  domProps: {
                    src: this.apiUrl + row.image
                  }
                });
              }
            },
            {
              title: '创建时间',
              key: 'gmt_create',
              render: (h, params) => {
                const row = params.row;
                const text = formatTime(row.gmt_create);
                return h('div', text);
              }
            },
            {
              title: '更新时间',
              key: 'gmt_modify',
              render: (h, params) => {
                const row = params.row;
                const text = formatTime(row.gmt_modify);
                return h('div', text);
              }
            },
            {
              title: '操作',
              width: 200,
              slot: 'action',
              align: 'center'
            }
          ],
          tableData: [],
          ruleValidate: {
            use_id: [
              { required: true, message: '用户id不能为空', trigger: 'blur' }
            ],
          },
          apiUrl: uploadUrl,
        }
    },
    computed: {
    },
    created() {},
    mounted() {
      
      this.normalUserID = 0;
      let user_type = store.state.userInfo.data.userData.user_type;
      if(user_type != 1){
        this.normalUserID = store.state.userInfo.data.userData.id;
      }
      this.getTaskList();
    },
    methods: {
      // 页码改变的回调，返回改变后的页码
      handleCurrentChange(val) {
        console.log(val)
        this.pageNo = val;
        this.getTaskList();
      },
      handlePageSizeChange(val) {
        console.log(val)
        this.pageSize = val;
        this.getTaskList();  
      },
      // 获取词汇包列表数据
      getTaskList() {
        this.loading = true;
  
        let data = {
          name: this.formFind.name,
          gmt_create: [formatDate(this.formFind.gmt_create[0]), formatDate(this.formFind.gmt_create[1])],
        }
        let params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          params: data
        }
  
        getBookList(params)
        .then(res => {
          console.log('词汇包列表===', res);
          this.loading = false;
          if (res.code == 0 && res.data) {
            this.tableData = res.data.rows;
            this.total = res.data.total;
          } else {
            this.tableData = [];
            this.total = 0;
          }
        })
        .catch(() => {
          this.loading = false;
        })
      },
      // 添加任务
      addTask() {
        this.isShow = true;
        this.textBtn = '提交';
        this.title = '添加词汇包';
        this.type = 1;
        
        this.$refs['formValidate'].resetFields();
      },
      // 编辑任务
      edit(index) {
        this.complete(index)

        this.textBtn = '保存';
        this.title = '编辑词汇包';
        this.type = 2;
      },
      // 详情
      complete(index) {
        this.isShow = true;
        this.title = '词汇包详情';
        this.type = 0;
        if( index < this.tableData.length){
          let row = this.tableData[index];
          this.formValidate = {
            id: row.id,
            name: row.name,
            gmt_create: formatTime(row.gmt_create),
            image: row.image,
          }
        }
      },
      // 删除任务
      innerRemove() {
        let data = {
          id: this.deleteId
        }
  
        deleteBook(data)
        .then(res => {
          console.log('删除词汇包===', res);
          if (res.code == 0) {
            this.pageNo = 1;
            this.getTaskList();
            this.$Message.success('词汇包删除成功');
          } else {
            this.$Message.error(res.msg);
          }
        })
      },
      // 删除任务
      remove(id) {
        let a = this;
        this.deleteId = id;
        this.$Modal.confirm({
          title: '确认删除这条数据吗？',
          onOk: function(){
            a.innerRemove()
          }
        })
      },

      // 提交添加或编辑
      handleSubmit(name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
  
            let data = {
              name: this.formValidate.name,
              image: this.formValidate.image,
              gmt_create: formatTime(this.formValidate.gmt_create),
            }
            if (this.type == 1) {
              addBook(data)
              .then(res => {
                console.log('添加词汇包===', res)
                this.isShow = false;
                if (res.code == 0) {
                  this.pageNo = 1;
                  this.getTaskList();
                  this.$Message.success(`${this.title}成功`);
                } else {
                  this.$Message.error(res.msg);
                }
              })
              .catch(() => {
                this.isShow = false;
              })
            } else if (this.type == 2) {
              data.id = this.formValidate.id;
  
              editBook(data)
              .then(res => {
                console.log('编辑词汇包===', res)
                this.isShow = false;
                if (res.code == 0) {
                  this.pageNo = 1;
                  this.getTaskList();
                  this.$Message.success(`${this.title}成功`);
                } else {
                  this.$Message.error(res.msg);
                }
              })
              .catch(() => {
                this.isShow = false;
              })
            }
  
          } else {
            return false;
          }
        })
      },
      // 重置表单
      handleReset (name) {
        this.$refs[name].resetFields();
      },
      // 只是为了美化一下导入按钮
      importTask: function() {
        this.$refs.upFileExcel.dispatchEvent(new MouseEvent('click'))
      },
      doImport(e) {
        const file = e.target.files[0]
        importBook(file).then(res => {
          if (res.code == 0) {
            this.pageNo = 1;
            this.getTaskList();
            this.$Message.success(`导入词汇包成功`);
          } else {
            this.$Message.error(res.msg);
          }
        })
        //this.$refs.upFileExcel.value = '';
      },
      doImportImage(e) {
        const file = e.target.files[0]
        uploadFile(file).then(res => {
          if (res.code == 0) {
            this.formValidate.image = res.data.newFilename;
          } else {
            this.$Message.error(res.msg);
          }
        })
        //this.$refs.upFileImage.value = '';
      }
    }
        
  }
  </script>
  
  <style lang="scss" scoped>
  .home-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .content {
      .list {
        display: flex;
        justify-content: space-between;
        align-content: center;
        Form {
          display: flex;
        }
      }
    }
  
  }	
  </style>
  <style lang="scss">
  .ivu-table-tip table td {
    width: 100% !important;
  }
  /*.ivu-input-icon-validate {
    display: none !important;
  }*/
  .pagination {
    float: right;
    margin: 20px 0;
  }
  
  .demo-drawer-footer{
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 16px;
    background: #fff;
    display: flex;
    justify-content: space-around;
  }
  </style>